package WaitNotify;


public class TestDemo3 {
    public static void main(String[] args) {
        GuardedTimeout guardedTimeout = new GuardedTimeout();
        Thread t1 = new Thread(()->{
            System.out.println("t1 计算中...");
            //最多等待2s中,等不到就不等了
            Integer x = guardedTimeout.get(3000);
            System.out.println("结果为 :"+ x);
        });
        t1.start();
        Thread t2 = new Thread(()->{
            int a = 10 + 90;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            guardedTimeout.take(null);
        });
        t2.start();
    }
}
//改进一下,加上一个超时机制,如果超过我等待的预期时间就不等了
class GuardedTimeout {
    private Integer response;
    public Integer get(long timeout){//最多等待2s
        synchronized (this) {
            long begin = System.currentTimeMillis();
            long passTime = 0;
            while (response == null) {
                long delay = timeout-passTime;
                if (delay<=0) {
                    break;
                }
                try {
                    //虚假唤醒就比如我要等待2s,它在1s的时候就唤醒了,但是
                    //我需要的response还是为null,而这个时候还没有到达我等待的时间
                    //所以再去等,等超过时间就break不等了
                    //防止虚假唤醒不能每次都等2s
                    //应该为 timeout - passTime才是真正要等待的时间
                    this.wait(delay);
                    System.out.println("等待中...");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passTime = System.currentTimeMillis() - begin;
            }
        }
        return response;
    }

    public void take(Integer response){
        synchronized (this){
            this.response = response;
            this.notifyAll();
        }
    }
}

